import React, { useState } from 'react'
import TypewriterText from './TypewriterText'
import PoemCard from './PoemCard'
import { generatePoemImage } from '../services/imageGeneration'
import { getPregeneratedShareCard, pregenerateShareCard } from '../services/sharePregeneration'

const OutputSection = ({ response, isLoading, userInput, generatedImage, isGeneratingImage, onToggleMainContent, onRestart, onImageGenerated, onRegenerateImage }) => {
  const [showEmotion, setShowEmotion] = useState(false)
  const [showAnalysis, setShowAnalysis] = useState(false)
  const [showImage, setShowImage] = useState(false)
  const [isGeneratingShare, setIsGeneratingShare] = useState(false)
  const [showCardMode, setShowCardMode] = useState(false)
  const [cardFlipped, setCardFlipped] = useState(false)
  const [showSharePreview, setShowSharePreview] = useState(false)
  const [shareCardDataUrl, setShareCardDataUrl] = useState(null)
  const [isTestingImage, setIsTestingImage] = useState(false)
  const [showFullUserInput, setShowFullUserInput] = useState(false)

  // CORS代理服务列表（与imageGeneration.js保持一致）
  const CORS_PROXIES = [
    'https://api.allorigins.win/raw?url=', // User's requested proxy format, often stable
    'https://cors-anywhere.herokuapp.com/', // Well-known and generally reliable
    'https://thingproxy.freeboard.io/fetch/', // Another common proxy
    'https://cors-server.fly.dev/', // A newer option found in search
    // 'https://cors-proxy.workers.dev/?apiUrl=', // This one requires specific setup, might be less general
  ]

  // 辅助函数：测试图片是否能实际加载
  const testImageLoad = (imageUrl) => {
    return new Promise((resolve) => {
      const img = new Image()
      const timeout = setTimeout(() => {
        img.onload = null
        img.onerror = null
        resolve(false)
      }, 8000) // 8秒超时

      img.onload = () => {
        clearTimeout(timeout)
        resolve(true)
      }

      img.onerror = () => {
        clearTimeout(timeout)
        resolve(false)
      }

      img.src = imageUrl
    })
  }

  // 辅助函数：通过fetch加载图片并返回blob URL
  const fetchImageAsBlob = async (originalUrl) => {
    // 尝试直接加载
    try {
      const response = await fetch(originalUrl)
      if (response.ok) {
        const blob = await response.blob()
        return URL.createObjectURL(blob)
      }
    } catch (error) {
      console.warn('⚠️ 直接加载图片失败:', error)
    }

    // 尝试通过代理加载
    for (const proxy of CORS_PROXIES) {
      try {
        let proxiedUrl
        const encodedOriginalUrl = encodeURIComponent(originalUrl)

        if (proxy.includes('?url=')) {
          proxiedUrl = `${proxy}${encodedOriginalUrl}`
        } else if (proxy.includes('?apiUrl=')) {
          proxiedUrl = `${proxy}${encodedOriginalUrl}`
        } else {
          proxiedUrl = `${proxy}${originalUrl}` // Default to path prefix
        }

        console.log('🔄 尝试通过代理加载图片:', proxiedUrl)
        const response = await fetch(proxiedUrl)
        if (response.ok) {
          const blob = await response.blob()
          return URL.createObjectURL(blob)
        }
      } catch (error) {
        console.warn(`⚠️ 代理 ${proxy} 加载失败:`, error)
      }
    }
    throw new Error('无法通过任何方式加载图片')
  }

  // 测试图片生成功能
  const handleTestImageGeneration = async () => {
    if (!response?.poem) {
      alert('请先生成诗句再测试图片生成')
      return
    }

    setIsTestingImage(true)
    console.log('🧪 开始测试图片生成...')

    try {
      const testResult = await generatePoemImage(
        response.poem,
        response.emotion || '诗意盎然',
        userInput
      )

      console.log('🧪 测试结果:', testResult)

      if (testResult.success) {
        alert(`✅ 图片生成测试成功！\n生成时间: ${testResult.generationTime?.toFixed(1)}s\n图片URL: ${testResult.imageUrl?.substring(0, 100)}...`)

        // 如果有回调函数，更新主应用的图片状态
        if (onImageGenerated) {
          onImageGenerated(testResult)
        }
      } else {
        alert(`❌ 图片生成测试失败：\n${testResult.error}`)
      }
    } catch (error) {
      console.error('🧪 测试图片生成失败:', error)
      alert(`❌ 测试失败：\n${error.message}`)
    } finally {
      setIsTestingImage(false)
    }
  }

  // 格式化诗句为四行显示
  const formatPoemLines = (poem) => {
    if (!poem) return []

    // 移除多余的空白字符，但保留换行符
    const cleanPoem = poem.replace(/[ \t]+/g, '').replace(/\n+/g, '\n')

    // 先按换行符分割
    let lines = cleanPoem.split('\n').filter(line => line.trim())

    // 如果行数不是4行，尝试重新分割
    if (lines.length !== 4) {
      // 合并所有文本
      const fullText = lines.join('')

      // 按标点符号分割
      const parts = fullText.split(/([，。！？；：])/g).filter(part => part.trim())

      // 重新组合成行
      const newLines = []
      let currentLine = ''

      for (let i = 0; i < parts.length; i++) {
        const part = parts[i]

        if (/[，。！？；：]/.test(part)) {
          // 是标点符号，加到当前行并结束这一行
          currentLine += part
          if (currentLine.trim()) {
            newLines.push(currentLine.trim())
            currentLine = ''
          }
        } else {
          // 是文字内容
          currentLine += part
        }
      }

      // 处理剩余内容
      if (currentLine.trim()) {
        newLines.push(currentLine.trim())
      }

      // 如果还是不是4行，进行调整
      if (newLines.length > 0) {
        if (newLines.length > 4) {
          // 超过4行，合并后面的行
          lines = newLines.slice(0, 3)
          lines.push(newLines.slice(3).join(''))
        } else if (newLines.length < 4 && newLines.length >= 2) {
          // 少于4行但有内容，尝试拆分长行
          lines = []
          for (const line of newLines) {
            if (line.length > 12 && lines.length < 3) {
              // 尝试在合适的位置拆分
              const mid = Math.floor(line.length / 2)
              let splitPos = mid

              // 寻找最近的标点符号作为分割点
              for (let j = mid; j < line.length && j < mid + 5; j++) {
                if (/[，。！？；：]/.test(line[j])) {
                  splitPos = j + 1
                  break
                }
              }

              lines.push(line.substring(0, splitPos))
              lines.push(line.substring(splitPos))
            } else {
              lines.push(line)
            }
          }

          // 确保不超过4行
          if (lines.length > 4) {
            const temp = lines.slice(0, 3)
            temp.push(lines.slice(3).join(''))
            lines = temp
          }
        } else {
          lines = newLines
        }
      }
    }

    // 最终确保是4行（如果内容足够的话）
    while (lines.length < 4 && lines.length > 0) {
      const lastLine = lines[lines.length - 1]
      if (lastLine.length > 8) {
        // 拆分最后一行
        const mid = Math.floor(lastLine.length / 2)
        lines[lines.length - 1] = lastLine.substring(0, mid)
        lines.push(lastLine.substring(mid))
      } else {
        break
      }
    }

    // 限制最多4行
    if (lines.length > 4) {
      lines = lines.slice(0, 4)
    }

    return lines
  }

  // 生成分享卡片预览 - 优先使用预生成的卡片
  const generateShareCardPreview = async () => {
    console.log('🔥 开始生成分享卡片预览...')
    console.log('📋 当前状态:', {
      hasPoem: !!response?.poem,
      isGenerating: isGeneratingShare,
      poem: response?.poem?.substring(0, 20) + '...',
      emotion: response?.emotion,
      userInput: userInput?.substring(0, 20) + '...',
      hasGeneratedImage: !!generatedImage?.success
    })

    if (!response?.poem) {
      console.error('❌ 没有诗句，无法生成分享卡片')
      alert('请先生成诗句')
      return
    }

    if (isGeneratingShare) {
      console.warn('⚠️ 正在生成中，跳过重复请求')
      return
    }

    setIsGeneratingShare(true)
    console.log('🎯 开始分享卡片生成流程')

    try {
      // 首先尝试获取预生成的分享卡片
      console.log('🔍 检查预生成的分享卡片...')
      const pregeneratedCard = getPregeneratedShareCard({
        poem: response.poem,
        emotion: response.emotion,
        userInput: userInput || ''
      })

      if (pregeneratedCard) {
        console.log('✅ 找到预生成的分享卡片，直接使用')
        setShareCardDataUrl(pregeneratedCard)
        setShowSharePreview(true)
        setIsGeneratingShare(false)
        return
      }

      console.log('🎨 预生成卡片未找到，开始实时生成...')
      console.log('📤 调用 pregenerateShareCard 函数...')

      // 验证浏览器支持Canvas
      if (!document.createElement('canvas').getContext) {
        throw new Error('浏览器不支持Canvas，无法生成分享卡片')
      }

      // 如果没有预生成的卡片，则实时生成
      const dataUrl = await pregenerateShareCard({
        poem: response.poem,
        emotion: response.emotion || '诗意盎然',
        userInput: userInput || '',
        generatedImage: generatedImage
      })

      console.log('🎨 pregenerateShareCard 返回结果:', dataUrl ? '成功' : '失败')

      if (dataUrl && dataUrl.startsWith('data:image/')) {
        console.log('✅ 分享卡片生成成功，显示预览')
        setShareCardDataUrl(dataUrl)
        setShowSharePreview(true)
      } else {
        console.error('❌ pregenerateShareCard 返回无效数据:', dataUrl?.substring(0, 50))
        throw new Error('分享卡片生成失败 - 返回数据无效')
      }

    } catch (error) {
      console.error('❌ 分享卡片生成过程中出错:', error)
      console.error('错误详情:', error.message, error.stack)

      let errorMessage = '生成分享卡片失败'
      if (error.message.includes('Canvas')) {
        errorMessage = '浏览器不支持Canvas功能'
      } else if (error.message.includes('网络')) {
        errorMessage = '网络连接问题，请稍后重试'
      } else if (error.message.includes('图片')) {
        errorMessage = '背景图片处理失败，但可以继续生成'
      }

      alert(`${errorMessage}: ${error.message}`)
    } finally {
      console.log('🏁 分享卡片生成流程结束')
      setIsGeneratingShare(false)
    }
  }

  // 下载分享卡片
  const downloadShareCard = () => {
    if (!shareCardDataUrl) return

    const link = document.createElement('a')
    link.href = shareCardDataUrl
    link.download = `诗词分享-${response.emotion}-${Date.now()}.jpg`
    link.click()
  }

  if (isLoading) {
    return (
      <section className="animate-slide-up">
        <div className="poem-display">
          <div className="text-center space-y-6">
            <h3 className="text-2xl font-semibold text-ink-700 font-chinese">
              AI正在感悟您的心语...
            </h3>
            
            {/* 加载动画 */}
            <div className="flex justify-center space-x-2">
              <div className="w-3 h-3 bg-gold-400 rounded-full animate-bounce"></div>
              <div className="w-3 h-3 bg-gold-400 rounded-full animate-bounce" style={{animationDelay: '0.1s'}}></div>
              <div className="w-3 h-3 bg-gold-400 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></div>
            </div>
            
            <p className="text-ink-500 italic">
              "诗意正在酝酿，请稍候片刻..."
            </p>
          </div>
        </div>
      </section>
    )
  }

  if (!response) return null

  return (
    <section className="animate-slide-up space-y-6">
      {/* 用户输入回显 */}
      <div className="bg-paper-100 border border-ink-200 rounded-lg p-4">
        <h3 className="text-lg font-medium text-ink-600 mb-2 font-chinese">您的心语：</h3>
        <div className="text-ink-700 italic leading-relaxed">
          <span>"{showFullUserInput || userInput.length <= 100 ? userInput : `${userInput.substring(0, 100)}...`}"</span>
          {userInput.length > 100 && (
            <button
              onClick={() => setShowFullUserInput(!showFullUserInput)}
              className="ml-2 text-gold-600 hover:text-gold-700 text-sm underline"
            >
              {showFullUserInput ? '收起' : '展开'}
            </button>
          )}
        </div>
      </div>

      {/* AI响应 */}
      <div className="poem-display space-y-8">
        {/* 抽卡模式 - 暂时隐藏 */}
        {false && showCardMode ? (
          <div className="flex justify-center">
            <PoemCard
              poem={response.poem}
              emotion={response.emotion}
              userInput={userInput}
              generatedImage={generatedImage}
              isVisible={true}
              onCardFlip={() => {
                setCardFlipped(true)
                setShowEmotion(true)
              }}
            />
          </div>
        ) : (
          /* 普通模式 - 诗句部分 */
          <div className="text-center">
            <h3 className="text-2xl font-semibold text-ink-700 font-chinese mb-6 ancient-title">
              为您而作
            </h3>

            <div className="bg-gradient-to-br from-paper-50 to-paper-100 border-2 border-gold-200 rounded-lg p-8 shadow-inner">
              <div className="text-2xl md:text-3xl leading-loose text-ink-800 poem-text space-y-3">
                {formatPoemLines(response.poem).map((line, index) => (
                  <div key={index} className="text-center">
                    <TypewriterText
                      text={line}
                      speed={80}
                      delay={index * 1000} // 每行延迟1秒开始
                      onComplete={index === formatPoemLines(response.poem).length - 1 ? () => setShowEmotion(true) : undefined}
                    />
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* 情绪标签 - 只在普通模式显示 */}
        {!showCardMode && showEmotion && (
          <div className="text-center animate-fade-in">
            <div className="inline-flex items-center space-x-2 bg-gold-100 border border-gold-300 rounded-full px-6 py-2 animate-bounce-gentle">
              <span className="text-gold-600 text-sm">情绪解读：</span>
              <TypewriterText
                text={response.emotion}
                speed={120}
                className="text-gold-800 font-medium"
                onComplete={() => setShowAnalysis(true)}
              />
            </div>
          </div>
        )}

        {/* 情绪分析 - 只在普通模式显示 */}
        {!showCardMode && showAnalysis && (
          <div className="bg-paper-50 border border-ink-200 rounded-lg p-6 animate-slide-up">
            <h4 className="text-lg font-medium text-ink-600 mb-3 font-chinese">AI的感悟：</h4>
            <p className="text-ink-700 leading-relaxed">
              <TypewriterText
                text={response.analysis}
                speed={50}
                onComplete={() => setShowImage(true)}
              />
            </p>
          </div>
        )}

        {/* 抽卡模式下的简化信息 - 暂时隐藏 */}
        {false && showCardMode && cardFlipped && (
          <div className="text-center animate-fade-in">
            <div className="bg-gradient-to-r from-purple-100 to-pink-100 border border-purple-200 rounded-lg p-4 max-w-md mx-auto">
              <h4 className="text-lg font-medium text-purple-800 mb-2">✨ 抽卡成功！</h4>
              <p className="text-purple-700 text-sm">
                您获得了一张 <span className="font-bold">{response.emotion}</span> 稀有度的诗词卡片
              </p>
            </div>
          </div>
        )}

        {/* 配图区域 */}
        {showImage && (
          <div className="animate-slide-up">
            <h4 className="text-xl font-semibold text-ink-700 font-chinese mb-4 text-center">
              诗意配图
            </h4>

            {isGeneratingImage ? (
              <div className="bg-paper-50 border-2 border-ink-200 rounded-lg p-8 text-center backdrop-blur-sm">
                <div className="flex flex-col items-center space-y-4">
                  <div className="relative">
                    <div className="w-16 h-16 border-4 border-gold-400 border-t-transparent rounded-full animate-spin"></div>
                    <div className="absolute inset-0 w-16 h-16 border-4 border-gold-200 rounded-full animate-pulse"></div>
                  </div>
                  <p className="text-ink-600 font-medium">
                    {generatedImage?.regenerating ? '🔄 正在重新生成配图...' : '🎨 AI正在为您的诗句绘制配图...'}
                  </p>
                  <p className="text-sm text-ink-400">
                    {generatedImage?.regenerating ? '使用新的创意视角重新绘制' : '运用传统水墨技法，融入情绪色彩'}
                  </p>
                  <div className="flex space-x-1">
                    <div className="w-2 h-2 bg-gold-400 rounded-full animate-bounce"></div>
                    <div className="w-2 h-2 bg-gold-400 rounded-full animate-bounce" style={{animationDelay: '0.1s'}}></div>
                    <div className="w-2 h-2 bg-gold-400 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></div>
                  </div>
                </div>
              </div>
            ) : generatedImage ? (
              <div className="bg-paper-50 border-2 border-ink-200 rounded-lg p-4 backdrop-blur-sm">
                {generatedImage.success ? (
                  <div className="space-y-4">
                    <div className="relative overflow-hidden rounded-lg shadow-xl group cursor-pointer"
                         onClick={() => onToggleMainContent(true)}>
                      <img
                        src={generatedImage.imageUrl}
                        alt="AI生成的诗意配图"
                        className="w-full h-auto max-h-96 object-cover transition-transform duration-500 group-hover:scale-105"
                        onError={(e) => {
                          e.target.style.display = 'none'
                          e.target.nextSibling.style.display = 'block'
                        }}
                      />
                      <div className="hidden bg-ink-100 p-8 text-center text-ink-500">
                        <div className="text-4xl mb-2">🖼️</div>
                        <p>图片加载失败，请稍后重试</p>
                      </div>

                      {/* 图片遮罩效果 */}
                      <div className="absolute inset-0 bg-gradient-to-t from-black/20 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>

                      {/* 图片标签 */}
                      <div className="absolute bottom-2 right-2 bg-black/50 text-white px-2 py-1 rounded text-xs backdrop-blur-sm">
                        点击查看全屏背景
                        {generatedImage.generationTime && (
                          <div className="text-xs opacity-75">
                            {generatedImage.generationTime.toFixed(1)}s
                          </div>
                        )}
                      </div>
                    </div>

                    {/* 重新生成按钮 - 成功状态下 */}
                    <div className="mt-4 text-center">
                      <button
                        onClick={() => onRegenerateImage && onRegenerateImage()}
                        disabled={isGeneratingImage}
                        className="px-4 py-2 bg-gradient-to-r from-green-500 to-teal-500 hover:from-green-600 hover:to-teal-600 text-white rounded-lg transition-all duration-200 text-sm font-medium shadow-md hover:shadow-lg transform hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {isGeneratingImage ? '🎨 重新生成中...' : '🔄 重新生成'}
                      </button>
                    </div>
                  </div>
                ) : (
                  <div className="text-center py-8">
                    <div className="text-6xl mb-4 opacity-50">🎨</div>
                    <div className="text-ink-500 mb-2 font-medium">配图生成遇到问题</div>
                    <p className="text-sm text-ink-400 mb-4">{generatedImage.error}</p>

                    {generatedImage.canRetry && (
                      <div className="bg-orange-50 border border-orange-200 rounded-lg p-3 mb-4">
                        <p className="text-sm text-orange-600 font-medium">💡 建议点击下方"重新生成图片"按钮重试</p>
                      </div>
                    )}

                    {/* 显示备用图片 */}
                    {generatedImage.fallbackImage && (
                      <div className="mt-4">
                        {generatedImage.fallbackImage.type === 'fallback' ? (
                          <div className="relative">
                            <img
                              src={generatedImage.fallbackImage.svg}
                              alt={generatedImage.fallbackImage.description}
                              className="mx-auto rounded-lg shadow-md max-w-md opacity-80"
                            />
                            <div className="absolute bottom-2 right-2 bg-black/50 text-white px-2 py-1 rounded text-xs">
                              情绪主题图案
                            </div>
                          </div>
                        ) : (
                          <img
                            src={generatedImage.fallbackImage}
                            alt="备用配图"
                            className="mx-auto rounded-lg opacity-60"
                          />
                        )}
                      </div>
                    )}

                    {/* 重新生成按钮 */}
                    <div className="mt-6">
                      <button
                        onClick={() => onRegenerateImage && onRegenerateImage()}
                        disabled={isGeneratingImage}
                        className="px-6 py-2 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white rounded-lg transition-all duration-200 text-sm font-medium shadow-lg hover:shadow-xl transform hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {isGeneratingImage ? '🎨 重新生成中...' : '🔄 重新生成图片'}
                      </button>
                    </div>

                    <p className="text-xs text-ink-300 mt-4">背景已应用情绪色彩，诗句依然完整</p>
                  </div>
                )}
              </div>
            ) : null}
          </div>
        )}

        {/* 操作按钮 */}
        <div className="flex justify-center flex-wrap gap-3">

          {/* 分享按钮 - 生成预览 */}
          <button
            onClick={generateShareCardPreview}
            disabled={isGeneratingShare}
            className="px-6 py-2 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white rounded-lg transition-all duration-200 text-sm font-medium shadow-lg hover:shadow-xl transform hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isGeneratingShare ? '🎨 生成中...' : '📤 分享诗词'}
          </button>

          <button
            onClick={onRestart}
            className="px-6 py-2 bg-gold-100 hover:bg-gold-200 text-gold-700 rounded-lg transition-colors duration-200 text-sm"
          >
            ✨ 重新开始
          </button>
        </div>

      </div>

      {/* 分享预览模态框 */}
      {showSharePreview && shareCardDataUrl && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-75 p-4">
          <div className="bg-white rounded-lg max-w-md w-full max-h-[90vh] overflow-auto">
            <div className="p-4">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold text-ink-700">分享预览</h3>
                <button
                  onClick={() => setShowSharePreview(false)}
                  className="text-ink-400 hover:text-ink-600 text-xl"
                >
                  ✕
                </button>
              </div>

              <div className="mb-4">
                <img
                  src={shareCardDataUrl}
                  alt="分享卡片预览"
                  className="w-full rounded-lg shadow-lg"
                />
              </div>

              <div className="flex gap-3">
                <button
                  onClick={downloadShareCard}
                  className="flex-1 px-4 py-2 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white rounded-lg transition-all duration-200 text-sm font-medium"
                >
                  📥 下载图片
                </button>
                <button
                  onClick={() => setShowSharePreview(false)}
                  className="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-lg transition-colors duration-200 text-sm"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </section>
  )
}

export default OutputSection
